package com.bw.module_detail

import android.content.pm.ActivityInfo
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.view.WindowInsets
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ReportFragment.Companion.reportFragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.viewpager2.widget.ViewPager2
import com.bw.lib_common.base.BaseMVIActivity
import com.bw.lib_common.livedata_eventbus.Events
import com.bw.lib_common.livedata_eventbus.LiveDataEventBus
import com.bw.lib_common.livedata_eventbuss.LiveEventBus
import com.bw.lib_common.utils.ToastUtils
import com.bw.lib_common.websocket.WebSocketUtils
import com.bw.lib_storage.UserMMKV
import com.bw.module_detail.adapter.FragmentAdapter
import com.bw.module_detail.fragment.CommentFragment
import com.bw.module_detail.fragment.VideoFragment
import com.bw.module_detail.intent.DetailIntent
import com.bw.module_detail.model.entity.DanMuEntity
import com.bw.module_detail.state.DetailSimpleState
import com.bw.module_detail.viewmodel.DetailViewModel
import com.bw.module_detail.databinding.ActivityMainnewBinding
import com.bw.module_detail.widget.DanMuBottomSheetDialog
import com.bw.module_detail.widget.RedPacketEnum
import com.bw.module_detail.widget.RedPacketEvent
import com.bw.module_detail.widget.RedPacketWidget
import com.google.android.exoplayer2.ExoPlayer
import com.google.android.exoplayer2.MediaItem
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.ui.AspectRatioFrameLayout
import com.google.android.exoplayer2.ui.PlayerView
import com.google.android.exoplayer2.ui.StyledPlayerView
import com.google.android.material.tabs.TabLayout
import com.google.gson.Gson
import com.tencent.mmkv.MMKV
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import master.flame.danmaku.controller.DrawHandler
import master.flame.danmaku.danmaku.model.BaseDanmaku
import master.flame.danmaku.danmaku.model.DanmakuTimer
import master.flame.danmaku.danmaku.model.IDanmakus
import master.flame.danmaku.danmaku.model.android.DanmakuContext
import master.flame.danmaku.danmaku.model.android.Danmakus
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser
import org.greenrobot.eventbus.EventBus
import org.java_websocket.handshake.ServerHandshake

@AndroidEntryPoint
class MainActivity : BaseMVIActivity() {
    private lateinit var redPacketWidget: RedPacketWidget
    private lateinit var exoPlayer: ExoPlayer
    private lateinit var playerView: StyledPlayerView
    private lateinit var list: MutableList<Fragment>
    private lateinit var fragmentAdapter: FragmentAdapter
    private lateinit var mViewModel: DetailViewModel
    private lateinit var videoPath:String
    private lateinit var icon:String
    private lateinit var name:String
    private lateinit var description:String
    private lateinit var duration:String
    private var albumId:Int? = 0
    var dataType:Int = 0 //视频类型
    var itemId:String = "6984351555034022414" //视频itemId
    private lateinit var dmContext: DanmakuContext //弹幕上下文
    private val dmParser: BaseDanmakuParser = object :BaseDanmakuParser(){ //弹幕解析器
        override fun parse(): IDanmakus {
            return Danmakus()
        }
    }
    private lateinit var webSocketUtils: WebSocketUtils
    private  val mBinding:ActivityMainnewBinding by lazy {
        ActivityMainnewBinding.inflate(layoutInflater)
    }
    private var isFullscreen = false // 横屏状态标志
    private var isFullscreen1 = false // 全屏状态标志

    override fun onCreate(savedInstanceState: Bundle?) {
        val intentVideoPath = intent.getStringExtra("videoPath")
        val intentIcon = intent.getStringExtra("icon")
        val intentName = intent.getStringExtra("name")
        val intentDescription = intent.getStringExtra("description")
        val intentDuration = intent.getStringExtra("duration")
        val intentAlbumId = intent.getIntExtra("albumId",0)

        videoPath = if (!intentVideoPath.isNullOrEmpty()){
            intentVideoPath
        }else{
            ""
        }
        if (intentIcon != null) {
            icon =intentIcon
        }
        if (intentDuration != null) {
            duration =intentDuration
        }
        if (intentName != null) {
            name =intentName
        }
        if (intentDescription != null) {
            description =intentDescription
        }
        albumId = intentAlbumId
        super.onCreate(savedInstanceState)
//        setupPlayer()

    }

    override fun generateViewModel() {
        mViewModel = ViewModelProvider(this)[DetailViewModel::class.java]
    }

    override fun getLayoutRootView(): View {
        return mBinding.root
    }


    override fun initView() {
        super.initView()
        initDanMu()
        initWebsocket() //初始化websocket

        mBinding.redView.setNum(100)

        //viewPager2切换Fragment
        list = mutableListOf<Fragment>()
        // 通过 ViewPager2 正确传递数据
        list = mutableListOf<Fragment>()
        val videoFragment = VideoFragment().apply {
            arguments = Bundle().apply {
                putString("icon", icon)
                putString("name", name)
                putString("desc", description)
                putString("num", duration)
            }
        }
        //打印
        Log.d("TAG", "initView: $icon $name $description $duration")
        list.add(videoFragment)
        list.add(CommentFragment())



        var tabList = mutableListOf<TabEntity>()
        tabList.add(TabEntity("简介", true))
        tabList.add(TabEntity("评论", false))

        //创建Exoplayer实例
        exoPlayer = ExoPlayer.Builder(this).build()
        //获取playerView
        playerView = findViewById(R.id.player)
        //将播放器关联到playerView
        playerView.player = exoPlayer

        //创建MediaItem
        val mediaItem = videoPath.let { MediaItem.fromUri(it) }
        // 设置媒体项到播放器
        exoPlayer.setMediaItem(mediaItem)

        // 准备播放器（异步）
        exoPlayer.prepare()
        exoPlayer.play()

        redPacketWidget = findViewById(R.id.red_view)
        redPacketWidget.setNum(100)
        redPacketWidget.setStateCallBack(object : RedPacketWidget.StateCallBack {
            override fun completed() {
//                 //上报金币
        mBinding.redView.setStateCallBack(object : RedPacketWidget.StateCallBack{
            override fun completed() {
                if (UserMMKV.token.isNullOrEmpty()){
                    showMsg("请先登录")
                    return
                }
                lifecycleScope.launch {
                    repeatOnLifecycle(Lifecycle.State.RESUMED){
                        val userId = UserMMKV.accountId
                        mViewModel.intents.send(DetailIntent.modifyCoinAmount(userId.toString(),100))
//                                    UserMMKV.accountId
                    }
                }
            }

        })
            }
        })

        exoPlayer.addListener(object : Player.Listener {
            override fun onPlaybackStateChanged(playbackState: Int) {
                super.onPlaybackStateChanged(playbackState)
                when(playbackState){
                    ExoPlayer.STATE_READY -> {
                        playerView.isVisible = true
                        EventBus.getDefault().post(
                            RedPacketEvent(
                                RedPacketEnum.INIT
                            )
                        )

                    }
                    ExoPlayer.STATE_ENDED -> {

//                        if (MMKV.isLooperPlay){//轮播
//                            exoPlayer.playbackLooper = true
//                        } else {//播放结束自动播放下一个
//
//                        }
                    }
                }
            }
            override fun onIsPlayingChanged(isPlaying: Boolean) {
                super.onIsPlayingChanged(isPlaying)
                if (isPlaying) {
                    EventBus.getDefault().post(RedPacketEvent(RedPacketEnum.RESUME))
                } else {
                    EventBus.getDefault().post(RedPacketEvent(RedPacketEnum.PAUSE))
                }
            }
        })


        val viewPager2 = findViewById<ViewPager2>(R.id.viewpager)
        fragmentAdapter = FragmentAdapter(this, list)
        viewPager2.adapter = fragmentAdapter

        // 获取TabLayout
        val tabLayout = findViewById<TabLayout>(R.id.tab)

        // 添加tabs
        tabList.forEach {
            val newTab = tabLayout.newTab()
            newTab.text = it.str  // 设置tab显示的文字
            tabLayout.addTab(newTab)
        }

        // 实现ViewPager2与TabLayout联动
        viewPager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                tabLayout.selectTab(tabLayout.getTabAt(position))
            }
        })

        // 实现TabLayout与ViewPager2联动
        tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                viewPager2.currentItem = tab?.position ?: 0
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {}

            override fun onTabReselected(tab: TabLayout.Tab?) {}
        })
    }
    private fun initWebsocket(){
        webSocketUtils = WebSocketUtils.Builder()
            .setUri("ws://10.161.9.80:7037/api/danmu/websocket/$itemId")
            .setReceiveMessageListener(object : WebSocketUtils.ReceiveMessageListener{
                override fun onMessage(message: String?) {
                    //接收到弹幕信息
//                    showMsg("接收到弹幕信息"+message)
                    //过滤掉心跳
                    if (message?.contains("heartbeat") == false){
                        val entity = Gson().fromJson<DanMuEntity>(message, DanMuEntity::class.java)
                        addDanMu(entity)
                    }

                }

                override fun onOpen(shake: ServerHandshake?) {
                    showMsg("打开链接")

                }

                override fun onClose(code: Int, reason: String?, remote: Boolean) {
                    showMsg("关闭链接")

                }

                override fun onError(ex: Exception?) {
//                    showMsg("链接失败"+ex?.message)

                }

            }).build()
    }
    override fun initData() {
        super.initData()
        //网络请求数据

        mBinding.dan.setOnClickListener {
            lifecycleScope.launch {
                repeatOnLifecycle(Lifecycle.State.RESUMED){ //页面活跃的时候处理流
                    mViewModel.intents.send(DetailIntent.getBulletScreenInfo(dataType, albumId.toString()))
                }
            }
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().post(RedPacketEvent(RedPacketEnum.STOP))
        //释放弹幕
        mBinding.danmakuView.release()

        // 2. 新增：彻底释放播放器资源（防止内存泄漏）
        if (::exoPlayer.isInitialized) {
            exoPlayer.stop() // 确保停止播放
            exoPlayer.release() // 释放播放器所有资源（关键）
        }
        // 3. 可选：解绑PlayerView与播放器（避免视图引用残留）
        if (::playerView.isInitialized) {
            playerView.player = null
        }
        //释放webSocket
        webSocketUtils.closeConnect()
        //释放红包资源
//        mBinding.redView.release()
    }

    override fun handleState() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED) {
                mViewModel.bulletScreenState_.collect {
                    when (it) {
                        is DetailSimpleState.Success -> {
                            //弹幕数据
                            for (entity in it.data) {
                                addDanMu(entity)
                            }
                        }

                        is DetailSimpleState.Error -> {
                            //弹幕数据错误
                            Log.d("弹幕数据错误", it.message)
                        }

                        is DetailSimpleState.Loading -> {

                        }

                        is DetailSimpleState.Empty -> {
                            //弹幕数据为空
                        }

                        is DetailSimpleState.Init -> {

                        }
                    }
                }
            }
        }
        //发布弹幕
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED){
                mViewModel.publishBulletScreenState_.collect{
                    when(it){
                        is DetailSimpleState.Success -> {
                            //弹幕发送成功
                            showMsg("弹幕发送成功")
                        }
                        is DetailSimpleState.Error -> {
                            //弹幕发送
                        }
                        is DetailSimpleState.Init -> {

                        }
                        is DetailSimpleState.Loading -> {

                        }

                        is  DetailSimpleState.Empty -> {

                        }
                    }
                }
            }
        }
        //上报金币
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED){
                lifecycleScope.launch {
                    repeatOnLifecycle(Lifecycle.State.RESUMED){
                        mViewModel.modifyCoinAmountState_.collect{
                            when(it){
                                is DetailSimpleState.Success -> {
                                    //红包发送成功
                                    showMsg("金币修改成功")
                                    //发送全局事件总线
                                    LiveDataEventBus.postEvent(Events.EVENT_RED_PACKET,true)
//                                    LiveEventBus.with<Boolean>(Events.EVENT_RED_PACKET).post(true)
                                }
                                is DetailSimpleState.Error -> {
                                    //红包发送失败
                                }
                                is DetailSimpleState.Init -> {

                                }
                                is DetailSimpleState.Loading -> {

                                }
                                is  DetailSimpleState.Empty -> {

                                }
                            }
                        }
                    }
                }
            }
        }
    }
    override fun initEvent() {
        super.initEvent()
        mBinding.danEd.setOnClickListener {
            val bottom = DanMuBottomSheetDialog()
            bottom.setDanMuListener(object : DanMuBottomSheetDialog.DanMuListener{

                override fun onClick() {
                    //1:本地显示弹幕信息
                    val content = bottom.etContent?.text.toString()
                    if (content.isBlank()){
                        showMsg("弹幕不能为空")
                        return
                    }
                    val entity = DanMuEntity(content = content, fontsize = 40, fontcolor = "#ff0000", datatype = dataType, itemid = albumId.toString())
                    addDanMu(entity)
                    //2：调用接口发送弹幕
                    lifecycleScope.launch {
                        repeatOnLifecycle(Lifecycle.State.RESUMED){
                            entity.playtime_ =  7 * 1000 //视频当前进度
                            mViewModel.intents.send(DetailIntent.publishBulletScreen(entity))
                        }
                    }
                    bottom.close()

                }
            })
            bottom.show(supportFragmentManager)
        }
        //点击下载视频
        mBinding.ivHomeDetailTv.setOnClickListener {
            //点击下载视频
            ToastUtils.showLong(this,"下载视频")

        }
        mBinding.btnFullscreen.setOnClickListener {
            val params = playerView.layoutParams
            params.width = ViewGroup.LayoutParams.MATCH_PARENT
            params.height = ViewGroup.LayoutParams.MATCH_PARENT
            playerView.layoutParams = params
            toggleFullscreen()
            //横屏之后红包

        }
        //全屏播放
        setupFullscreenListener()


    }

    private fun setupFullscreenListener() {
        // StyledPlayerView 有内置的全屏按钮监听器
        playerView.setFullscreenButtonClickListener {
            isFullscreen1 = !isFullscreen1

            if (isFullscreen1) {
                enterPortraitFullscreen()
            } else {
                exitPortraitFullscreen()
            }
        }
    }
    private fun enterPortraitFullscreen() {
        // 保持竖屏，但隐藏所有系统UI
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT

        // 隐藏状态栏和导航栏
        hideSystemUI()
         
        // 调整PlayerView为全屏尺寸
        val params = playerView.layoutParams
        params.width = ViewGroup.LayoutParams.MATCH_PARENT
        params.height = ViewGroup.LayoutParams.MATCH_PARENT
        playerView.layoutParams = params

        // 可选：隐藏ActionBar/Toolbar
        supportActionBar?.hide()
    }

    private fun exitPortraitFullscreen() {
        // 显示系统UI
        showSystemUI()

        // 恢复PlayerView原始尺寸
        val params = playerView.layoutParams
        params.width = ViewGroup.LayoutParams.MATCH_PARENT
        params.height = resources.getDimensionPixelSize(R.dimen.dp_200) // 例如：300dp

        playerView.layoutParams = params

        // 显示ActionBar/Toolbar
        supportActionBar?.show()
    }


    private fun toggleFullscreen() {
        isFullscreen = !isFullscreen

        if (isFullscreen) {
            // 进入全屏
            requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
            hideSystemUI()


        } else {
            // 退出全屏
            requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
            showSystemUI()
        }
    }
    private fun hideSystemUI() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            window.insetsController?.hide(WindowInsets.Type.statusBars() or WindowInsets.Type.navigationBars())
        } else {
            @Suppress("DEPRECATION")
            window.decorView.systemUiVisibility = (
                    View.SYSTEM_UI_FLAG_FULLSCREEN or
                            View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
                            View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    )
        }
    }

    private fun showSystemUI() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            window.insetsController?.show(WindowInsets.Type.statusBars() or WindowInsets.Type.navigationBars())
        } else {
            @Suppress("DEPRECATION")
            window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE
        }
    }

    /**
     * 初始化弹幕
     */
    private fun initDanMu() {
        //设置最大显示行数
        val max:HashMap<Int, Int> = HashMap()
        max[BaseDanmaku.TYPE_SCROLL_RL] = 8 //设置最大显示行数
        //设置是否禁止重叠
        val over:HashMap<Int,Boolean> = HashMap()
        over[BaseDanmaku.TYPE_SCROLL_RL] = true
        //创建弹幕上下文
        dmContext = DanmakuContext.create()
        //设置弹幕属性
        dmContext.setDuplicateMergingEnabled(false)
            .setScrollSpeedFactor(1.2f)
            .setScaleTextSize(1.2f)
//            .setCacheStuffer(IGSYRenderView.SimpleCacheStuffer(),)
            .setMaximumLines(max) //最大行数
            .preventOverlapping(over) //防止重叠

        mBinding.danmakuView.setCallback(object : DrawHandler.Callback{
            override fun prepared() {
                //准备完成播放弹幕
                mBinding.danmakuView.start()
                Log.d("TAG", "prepared: ")
            }

            override fun updateTimer(p0: DanmakuTimer?) {

            }

            override fun danmakuShown(p0: BaseDanmaku?) {

            }

            override fun drawingFinished() {

            }
        })
        mBinding.danmakuView.prepare(dmParser,dmContext) //准备弹幕
        mBinding.danmakuView.enableDanmakuDrawingCache( true) //缓存弹幕

    }


    /**
     * 添加弹幕信息
     */
    private fun addDanMu(entity: DanMuEntity){
        //创建一条弹幕
        val  danMu:BaseDanmaku = dmContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL)
        //设置弹幕属性
        if (entity.fontsize == 0){
            danMu.textSize = 35f
        }else{
            danMu.textSize = entity.fontsize.toFloat() //字体大小
        }

        if(entity.fontcolor.isNullOrEmpty()){
            danMu.textColor = Color.WHITE
        }else{
            danMu.textColor = Color.parseColor(entity.fontcolor) //字体颜色
        }

        danMu.text = entity.content //内容
        danMu.time = mBinding.danmakuView.currentTime + entity.playtime_
        danMu.padding = 10
        //其他属性
        //添加弹幕
        mBinding.danmakuView.addDanmaku(danMu)
    }

    override fun onPause() {
        super.onPause()
        //暂停弹幕绘制
        if (mBinding.danmakuView.isPrepared){
            mBinding.danmakuView.pause()
        }
    }

    override fun onResume() {
        super.onResume()
        //继续弹幕绘制
        if (mBinding.danmakuView.isPrepared && mBinding.danmakuView.isPaused){
            mBinding.danmakuView.resume()
        }
    }

}
data class TabEntity(
    var str:String,
    var isShow:Boolean
)